<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Repositories\Role\RoleRepository;
use App\Repositories\Permission\PermissionRepository;

class RoleController extends Controller {

	protected $role;
	protected $permission;

	public function __construct(RoleRepository $role, PermissionRepository $permission) {
		$this->role       = $role;
		$this->permission = $permission;
	}

	/**
	 * Display a listing of the resource.
	 * @return Response
	 */
	public function index() {

		$list = $this->role->paginate();

		return view('admin.role.index', compact('list'));
	}

	/**
	 * Show the form for creating a new resource.
	 * @return Response
	 */
	public function create() {
		return view('admin.role.create');
	}

	/**
	 * Store a newly created resource in storage.
	 * @return Response
	 */
	public function store(Request $request) {

		$role = $this->role->create($request->all());

		if ($role) {
			success('添加成功');
		} else {
			error('添加失败');
		}
	}

	/**
	 * Display the specified resource.
	 * @param  int $id
	 * @return Response
	 */
	public function show($id) {
		//
	}

	/**
	 * Show the form for editing the specified resource.
	 * @param  int $id
	 * @return Response
	 */
	public function edit($id) {
		$data = $this->role->find($id);
		return view('admin.role.edit', compact('data'));
	}

	/**
	 * Update the specified resource in storage.
	 * @param  int $id
	 * @return Response
	 */
	public function update(Request $request, $id) {
		$result = $this->role->update($request->all(), $id);

		if ($result) {
			success('修改成功');
		} else {
			error('修改失败');
		}
	}


	/**
	 * 分配权限
	 * @param Request $request
	 * @param         $id
	 * @return \Illuminate\View\View
	 */
	public function AssignPermission(Request $request, $id) {

		$permissions = $this->permission->all(['id', 'display_name']);

		$role = $this->role->find($id);

		if ($request->isMethod('post')) {

			$permissionIds = $request->input('permissionIds',array());

			if ($this->role->assignPermission($id,$permissionIds)) {
				success('权限分配成功');
			} else {
				error('权限分配失败');
			};

		};

		return view('admin.role.assign_permission', compact('permissions', 'id','role'));
	}

	/**
	 * Remove the specified resource from storage.
	 * @param  int $id
	 * @return Response
	 */
	public function destroy($id) {
		//
	}
}
